package us.mooresr.geartrack.client.core.desktop;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import us.mooresr.geartrack.client.core.presenter.BorrowPresenter;
import us.mooresr.geartrack.client.core.presenter.BorrowPresenter.MyView;
import us.mooresr.geartrack.client.core.presenter.BorrowUiHandlers;
import us.mooresr.geartrack.shared.model.DatastoreObject;
import us.mooresr.geartrack.shared.model.Person;
import us.mooresr.geartrack.shared.model.Item;

import com.gwtplatform.mvp.client.ViewImpl;
import com.gwtplatform.mvp.client.ViewWithUiHandlers;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;

public class DesktopBorrowViewImpl extends ViewWithUiHandlers<BorrowUiHandlers> 
	implements BorrowPresenter.MyView, ContentWidgetEventHandler {

	private final Widget widget;
	private final ContentWidget contentWidget;
	@UiField HTMLPanel contentPanel;
	private BorrowForm borrowForm;
	private Item selectedItem;

	public interface Binder extends UiBinder<Widget, DesktopBorrowViewImpl> {
	}

	@Inject
	public DesktopBorrowViewImpl(final Binder binder, final EventBus eventBus) {
		widget = binder.createAndBindUi(this);
		contentWidget = GWT.create(ContentWidget.class);
		contentWidget.setTitle("Borrow an Item");
		contentWidget.setButtonText(1, "Check Out");
		contentWidget.hideButton(2);
		contentWidget.hideButton(3);
		contentPanel.add(contentWidget);
		
		contentWidget.setHandler(this);
		
		borrowForm = new BorrowForm();
		contentWidget.setContent(borrowForm);


	}

	@Override
	public Widget asWidget() {
		return widget;
	}

	@Override
	public void setItems(List<Item> list) {
		
		// TODO:  Add support for filtering?
		
		contentWidget.setListContents(list);
		
	}
	
	@Override
	public void setPeople(List<Person> people) {
		borrowForm.setPeople(people);
	}

	@Override
	public void onSelection(DatastoreObject selectedObject) {
		selectedItem = (Item) selectedObject;
		
	}

	@Override
	public void onButton1Click() {
		// Check out button 
		if (selectedItem == null) {
			return;
		}
		
		Long borrowerId = borrowForm.getPersonId();
		getUiHandlers().borrowItem(selectedItem.getId(), borrowerId);
		
		
		
	}

	@Override
	public void onButton2Click() {
		// Button 2 is not used
		
	}

	@Override
	public void onButton3Click() {
		// Button 3 is not used
		
	}

	/**
	 * Called when a checkout is successful and the item should be removed from the list
	 */
	@Override
	public void removeItem(Item item) {
		contentWidget.removeItemFromList(item);
		
	}


}
